<template>
	<view>
		<TopNav title="生产记录"></TopNav>
		<u-form class="padding-lr-sm padding-bottom" labelWidth="88px" :model="form" ref="form" :rules="rules">
			<view class="padding-tb">
				<text class="cuIcon-title text-gray"></text>
				<text class="">基本信息</text>
			</view>

			<view class="padding-tb-xs padding-lr radius bg-white">
				<u-form-item label="塘口" required @click="handleOpenPondSelect" prop="culturePondId">
					<u-input v-model="form.culturePondName" border="none" inputAlign="right" placeholder="选择塘口" readonly
						class="pointer-none">
						<u-icon slot="suffix" name="arrow-right"></u-icon>
					</u-input>
				</u-form-item>
			</view>
			<view class="padding-tb-xs padding-lr radius bg-white margin-top">
				<u-form-item label="时间" borderBottom required @click="handleOpenDateSelect" prop="time">
					<u-input :value="form.time" border="none" inputAlign="right" placeholder="选择记录时间" re
						class="pointer-none">
						<u-icon slot="suffix" name="arrow-right"></u-icon>
					</u-input>
				</u-form-item>
				<u-form-item label="天气" borderBottom required prop="weather">
					<u-input v-model="form.weather" border="none" placeholder="填写天气状况" inputAlign="right"
						:disabled="!form.culturePondId"></u-input>
				</u-form-item>
				<u-form-item label="pH值" borderBottom required prop="ph">
					<u-input v-model="form.ph" border="none" placeholder="填写pH值" inputAlign="right"
						:disabled="!form.culturePondId"></u-input>
				</u-form-item>
				<u-form-item label="透明度" borderBottom required prop="transparency">
					<u-input v-model="form.transparency" border="none" placeholder="填写水体透明度" inputAlign="right"
						:disabled="!form.culturePondId">
						<text slot="suffix">m</text>
					</u-input>
				</u-form-item>
				<u-form-item label="平均水温" required prop="waterTemperature">
					<u-input v-model="form.waterTemperature" border="none" placeholder="填写平均水温" inputAlign="right"
						:disabled="!form.culturePondId">
						<text slot="suffix">℃</text>
					</u-input>
				</u-form-item>
			</view>
			<view class="padding-tb flex justify-between">
				<view class="">
					<text class="cuIcon-title text-gray"></text>
					<text class="">投喂情况</text>
				</view>
				<view class="text-right">
					<text class="text-gray text-width">饲料规格：</text>
					<text class="text-orange">{{specifications}}{{specificationsUnitDictName || '-'}}</text>
				</view>
			</view>
			
			<view class="padding-tb-xs padding-lr radius bg-white">
				<u-form-item label="饲料品种" borderBottom required prop="feedstuffId" @click="handleOpenFeedSelect">
					<u-input v-model="form.feedstuffName" border="none" inputAlign="right" placeholder="选择使用饲料" readonly
						class="pointer-none" :disabled="!form.culturePondId">
						<u-icon slot="suffix" name="arrow-right"></u-icon>
					</u-input>
				</u-form-item>
				<u-form-item label="投喂量" borderBottom required prop="feedstuffUsage">
					<u-input v-model="form.feedstuffUsage" border="none" placeholder="填写投喂量" inputAlign="right"
						:formatter="formatNumber" :disabled="!form.feedstuffId">
						<view slot="suffix" class="" style="width: 50px;">
							<DictPicker :dict="outboundUnits" v-model="form.feedstuffUsageUnit" placeholder="单位"
								:disabled="!form.feedstuffId">
							</DictPicker>
						</view>
					</u-input>
				</u-form-item>
				<u-form-item label="饲(饵)来源" prop="feedstuffManufacturer">
					<u-input v-model="form.feedstuffManufacturer" border="none" inputAlign="right"
						placeholder="选择使用饲料自动填写" readonly class="pointer-none">
					</u-input>
				</u-form-item>

			</view>
			
			<view class="padding-tb-xs padding-lr radius bg-white margin-top">
				<u-form-item label="备注" labelPosition="top">
					<u-textarea v-model="form.remarks" border="bottom" placeholder="填写备注信息" autoHeight
						:disabled="!form.culturePondId"></u-textarea>
				</u-form-item>

			</view>
			<view class="padding-tb">
				<text class="cuIcon-title text-gray"></text>
				<text class="">相关图片</text>
			</view>
			<view class="padding radius bg-white">
				<UploadImage v-model="form.fileUrls" :limit="9" :disabled="!form.culturePondId"></UploadImage>
			</view>
		</u-form>
		<view class="bottom-tools padding flex justify-around bg-white">
			<van-button class='basis-sm' plain hairline type="info" @click="handleSubmit('save')">保存</van-button>
			<van-button class='basis-sm' type="primary" @click="handleSubmit('submit')">
				提交
			</van-button>
		</view>
		<u-datetime-picker :show="dateShow" :value="timestampFormat" mode="datetime" closeOnClickOverlay
			:maxDate="maxDate" :minDate="minDate" @close="handleCloseDateSelect" @cancel="handleCloseDateSelect"
			@confirm="handleConfirmDateSelect"></u-datetime-picker>

	</view>
</template>

<script>
	import UploadImage from "@/components/upload-image.vue"
	import dayjs from 'dayjs'
	import {
		monitoringFactors,
		detail,
		add,
		update
	} from "@/api/work/production"
	import DictPicker from '@/components/dict-picker/index.vue'

	export default {
		components: {
			UploadImage,
			DictPicker
		},
		data() {
			return {
				specifications:'',
				specificationsUnitDictName: '',
				maxDate: dayjs().valueOf(),
				minDate: dayjs('2024-01-01 00:00').valueOf(),
				dateShow: false,
				queryParams: {
					id: undefined
				},
				form: {
					culturePondId: undefined,
					culturePondName: undefined,
					time: dayjs().format('YYYY-MM-DD HH:mm'),
					weather: undefined,
					ph: undefined,
					transparency: undefined,
					waterTemperature: undefined,
					feedstuffId: undefined,
					feedstuffName: undefined,
					feedstuffUsage: undefined,
					feedstuffUsageUnit: undefined,
					feedstuffManufacturer: undefined,
					submitMark: undefined,
					remarks: undefined,
					fileUrls: undefined
				},
				rules: {
					culturePondId: {
						type: 'string',
						required: true,
						message: '塘口不能为空',
						trigger: ['blur', 'change']
					},
					time: {
						type: 'string',
						required: true,
						message: '记录时间不能为空',
						trigger: ['blur', 'change']
					},
					weather: {
						type: 'string',
						required: true,
						message: '天气不能为空',
						trigger: ['blur', 'change']
					},
					ph: {
						type: 'number',
						required: true,
						message: 'pH值不能为空',
						trigger: ['blur', 'change']
					},
					transparency: {
						type: 'number',
						required: true,
						message: '透明度不能为空',
						trigger: ['blur', 'change']
					},
					waterTemperature: {
						type: 'number',
						required: true,
						message: '平均水温不能为空',
						trigger: ['blur', 'change']
					},
					feedstuffId: {
						type: 'string',
						required: true,
						message: '饲料品种不能为空',
						trigger: ['blur', 'change']
					},
					feedstuffUsage: {
						type: 'number',
						required: true,
						message: '投喂量不能为空',
						trigger: ['blur', 'change']
					}
				}

			}
		},
		computed: {
			timestampFormat() {
				return dayjs(this.form.time).valueOf()
			},
			outboundUnits() {
				let str = this.specificationsUnitDictName
				if (str.includes('/')) {
					// 如果有，则按照 '/' 分割
					let array = str.split('/');
					let result = array.map(item => {
						return {
							value: item,
							text: item
						}
					})
					return result
				} else {
					// 如果没有，则返回原值组成的数组
					return [{
						text: str,
						value: str
					}];
				}
			}
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.form.setRules(this.rules)
		},
		onLoad(query) {
			if (query.id) {
				this.queryParams.id = query.id
				this.getDetail()
			}
		},
		onShow() {

		},
		onUnload() {
			uni.$off('feedSelect', this.receiveFeedSelect)
			uni.$off('pondSelect', this.receivePondSelect)
		},
		methods: {
			formatNumber(input) {
				// 将输入转为数字类型
				let number = parseFloat(input);
				// 判断是否是有效的数字
				if (isNaN(number)) {
					return input; // 如果不是数字，直接返回原字符串
				}
				// 判断小数部分的位数
				if (number % 1 !== 0) {
					// 如果是浮动数，格式化为一位小数
					return number.toFixed(1);
				} else {
					// 如果是整数，直接返回原字符
					return input;
				}
			},
			receiveFeedSelect(val) {
				if (val.length === 0) {
					this.form.feedstuffId = undefined
					this.form.feedstuffName = undefined
					return
				}
				let {
					id,
					name,
					specifications,
					specificationsUnitDictName,
					manufacturer
				} = val[0]
				this.specifications = specifications
				this.specificationsUnitDictName = specificationsUnitDictName
				this.form.feedstuffId = id
				this.form.feedstuffName = name
				this.form.feedstuffManufacturer = manufacturer
			},
			handleOpenFeedSelect() {
				uni.$on('feedSelect', this.receiveFeedSelect)
				this.$tab.navigateTo('/pages/work/feed-inventory/select?id=' + this.form.feedstuffId)
			},
			handleSubmit(type) {
				this.$refs.form.validate().then(res => {
					this.form.submitMark = false
					if (type === 'submit') this.form.submitMark = true
					if (this.form.id) {
						update(this.form).then(res => {
							this.$modal.msgSuccess('修改成功')
						})
					} else {
						add(this.form).then(res => {
							if (type === 'save') {
								this.$modal.msgSuccess('已保存，可在草稿箱中查看')
							} else {
								this.$tab.navigateBack()
							}
						})
					}
				})

			},
			getDetail() {
				detail(this.queryParams).then(res => {
					this.form = res.data
					this.specifications = res.data.feedstuffSpecifications
					this.specificationsUnitDictName = res.data.feedstuffSpecificationsUnitDictName
				})
			},

			handleCloseDateSelect() {
				this.dateShow = false
			},
			handleConfirmDateSelect(date) {
				this.form.time = dayjs(date.value).format('YYYY-MM-DD HH:mm')
				this.dateShow = false
			},
			handleOpenDateSelect() {
				this.dateShow = true
			},
			getMonitoringFactors() {
				monitoringFactors({
					id: this.form.culturePondId
				}).then(res => {
					// 快速填充表单
					for (let key in res.data) {
						if (this.form.hasOwnProperty(key)) {
							this.form[key] = res.data[key];
						}
					}
					this.specifications = res.data.feedstuffSpecifications
					this.specificationsUnitDictName = res.data.feedstuffSpecificationsUnitDictName
				})
			},
			receivePondSelect(val) {
				if (val.length === 0) {
					this.reset()
					return
				}
				let {
					culturePondId,
					culturePondName
				} = val[0]
				this.form.culturePondId = culturePondId
				this.form.culturePondName = culturePondName
				this.getMonitoringFactors()
			},
			handleOpenPondSelect() {
				uni.$on('pondSelect', this.receivePondSelect)
				this.$tab.navigateTo('/pages/mine/pond/select?pondId=' + this.form.culturePondId)
			},
			reset() {
				this.form = {
					culturePondId: undefined,
					culturePondName: undefined,
					time: dayjs().format('YYYY-MM-DD HH:mm'),
					weather: undefined,
					ph: undefined,
					transparency: undefined,
					waterTemperature: undefined,
					feedstuffId: undefined,
					feedstuffName: undefined,
					feedstuffUsage: undefined,
					feedstuffUsageUnit: undefined,
					feedstuffManufacturer: undefined,
					submitMark: undefined,
					remarks: undefined,
					fileUrls: undefined
				}
				this.$nextTick(() => {
					this.$refs.form.resetFields()
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "@/common/var.scss";
	page {
		@include fixed-bottom;
	}
	
</style>